/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.UserSchedulingConfigAddDTO;
import org.springblade.modules.admin.entity.MaintainTemplateHistory;
import org.springblade.modules.admin.entity.MaintainTemplateSceneType;
import org.springblade.modules.admin.entity.UserSchedulingConfig;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainTemplateHistoryService;
import org.springblade.modules.admin.service.IMaintainTemplateSceneTypeService;
import org.springblade.modules.admin.vo.MaintainTemplateSceneTypeVO;
import org.springblade.modules.admin.vo.UserSchedulingConfigVO;
import org.springblade.modules.admin.mapper.UserSchedulingConfigMapper;
import org.springblade.modules.admin.service.IUserSchedulingConfigService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员维保排期关注配置 服务实现类
 *
 * @author ysq
 * @since 2023-12-14
 */
@Service
public class UserSchedulingConfigServiceImpl extends BaseServiceImpl<UserSchedulingConfigMapper, UserSchedulingConfig> implements IUserSchedulingConfigService {

	@Autowired
	IMaintainTemplateSceneTypeService maintainTemplateSceneTypeService;

	@Autowired
	IMaintainTemplateHistoryService templateHistoryService;

	/**
	 * 当前用户关注配置
	 * 2023-12-20 格式变更
	 * @param userSchedulingConfig 用户配置入参
	 * @return 是否成功
	 */
	@Override
	public Boolean saveOrUpdateConfig(UserSchedulingConfigAddDTO userSchedulingConfig) {
		// 0. 参数准备
		Map<String,List<MaintainTemplateSceneTypeVO>> targetMap = new HashMap<>(4);

		// 1. 获取入参，将入参相关创建对象并插入，转换成Json格式
		List<MaintainTemplateSceneTypeVO> disableConfig = new ArrayList<>();
		List<MaintainTemplateSceneTypeVO> unfinishedConfig = new ArrayList<>();
		List<MaintainTemplateSceneTypeVO> finishedConfig = new ArrayList<>();

		if (Func.isNotEmpty(userSchedulingConfig.getDisableConfig())) {
			userSchedulingConfig.getDisableConfig().forEach(e -> {
				MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
				vo.setId(Long.valueOf(e));
				disableConfig.add(vo);
			});
		}
		if (Func.isNotEmpty(userSchedulingConfig.getUnfinishedConfig())) {
			userSchedulingConfig.getUnfinishedConfig().forEach(e -> {
				MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
				vo.setId(Long.valueOf(e));
				unfinishedConfig.add(vo);
			});
		}
		if (Func.isNotEmpty(userSchedulingConfig.getFinishedConfig())) {
			userSchedulingConfig.getFinishedConfig().forEach(e -> {
				MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
				vo.setId(Long.valueOf(e));
				finishedConfig.add(vo);
			});
		}
		if (Func.isNotEmpty(disableConfig)) {
			targetMap.put("disableConfig",disableConfig);
		}
		if (Func.isNotEmpty(unfinishedConfig)) {
			targetMap.put("unfinishedConfig",unfinishedConfig);
		}
		if (Func.isNotEmpty(finishedConfig)) {
			targetMap.put("finishedConfig",finishedConfig);
		}
		// 2. 将Json格式存入数据库
		Long userId = AuthUtil.getUserId();
		UserSchedulingConfig userSchedulingConfigEntity = new UserSchedulingConfig();
		userSchedulingConfigEntity.setUserId(userId);
		userSchedulingConfigEntity.setConfig(Func.toJson(targetMap));
		// 3. 根据当前用户id，查询是否存在配置信息，存在则更新（先删除，再重新新增），不存在则之间新增
		UserSchedulingConfig config = this.getOne(new LambdaQueryWrapper<UserSchedulingConfig>()
			.eq(UserSchedulingConfig::getUserId, userId)
			.eq(UserSchedulingConfig::getIsDeleted, 0)
		);
		if(!Func.isNull(config)){
			// 先删除再更新
			this.removeById(config.getId());
        }
        return this.save(userSchedulingConfigEntity);
    }

	/**
	 * 当前用户查配置信息查询列表
	 * @return 查询列表
	 */
	@Override
	public UserSchedulingConfigVO listAll(Integer status) {
		// 0. 数据准备
		UserSchedulingConfigVO userSchedulingConfigVO = new UserSchedulingConfigVO();
		List<MaintainTemplateSceneTypeVO> result = new ArrayList<>();
		Long userId = AuthUtil.getUserId();
		userSchedulingConfigVO.setUserId(userId);
		// 1. 待开始配置列表,复用璟哥方法
		if (status.equals(TaskStatusEnum.BY_DISABLE.getStatus())) {
			List<MaintainTemplateSceneType> list = maintainTemplateSceneTypeService.list();
			if (Func.isNotEmpty(list)) {
				List<MaintainTemplateSceneTypeVO> finalResult = new ArrayList<>();
				list.forEach(e -> {
					MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
					vo.setId(e.getId());
					vo.setName(e.getName());
					vo.setDesc(e.getDesc());
					vo.setMaintainType(e.getMaintainType());
					vo.setSort(e.getSort());
					finalResult.add(vo);
				});
				result.addAll(finalResult);
				if(Func.isNotEmpty(result))	{
					result = result.stream()
						.sorted(Comparator.comparing(MaintainTemplateSceneTypeVO::getSort))
						.collect(Collectors.toList());
				}
			}
			userSchedulingConfigVO.setDisableConfig(result);
			userSchedulingConfigVO.setFinishedConfig(new ArrayList<>());
			userSchedulingConfigVO.setUnfinishedConfig(new ArrayList<>());
			return userSchedulingConfigVO;
		}
		// 2. 未完成配置列表
		if(new Integer(2).equals(status)){
			// 根据未完成工单反查
			List<MaintainTemplateHistory> unfinishedConfig = templateHistoryService.listUnfinishedConfig();
			if(Func.isNotEmpty(unfinishedConfig)){
				List<MaintainTemplateSceneTypeVO> finalResult = new ArrayList<>();
				unfinishedConfig.forEach(e -> {
					MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
					vo.setId(e.getTemplateSceneTypeId());
					vo.setName(e.getTemplateSceneTypeName());
					vo.setDesc(e.getTemplateSceneTypeDesc());
					vo.setSortTime(e.getCreateTime());
					finalResult.add(vo);
				});
				result = finalResult.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(e -> e.getId() + ";" + e.getName()))),ArrayList::new));
				result = result.stream().sorted(Comparator.comparing(MaintainTemplateSceneTypeVO::getSortTime).reversed()).collect(Collectors.toList());
			}
			userSchedulingConfigVO.setUnfinishedConfig(result);
			userSchedulingConfigVO.setFinishedConfig(new ArrayList<>());
			userSchedulingConfigVO.setDisableConfig(new ArrayList<>());
			return userSchedulingConfigVO;
		}
		// 3. 已完成配置列表
		if(new Integer(3).equals(status)){
			// 根据已完成工单反查注意，已完成工单配置列表，时间为一年已完成配置列表，根据planStatus动态查询,注意，已完成工单配置列表，时间为一年
			LocalDateTime now = LocalDateTime.now();
			LocalDateTime lastYear = now.minusYears(1);
			String beginTime = lastYear.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
			String endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
			List<MaintainTemplateHistory> finishedConfig = templateHistoryService.listFinishedConfig(beginTime,endTime);
			if(Func.isNotEmpty(finishedConfig)){
				List<MaintainTemplateSceneTypeVO> finalResult = new ArrayList<>();
				finishedConfig.forEach(e -> {
					MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
					vo.setId(e.getTemplateSceneTypeId());
					vo.setName(e.getTemplateSceneTypeName());
					vo.setDesc(e.getTemplateSceneTypeDesc());
					vo.setSortTime(e.getCreateTime());
					finalResult.add(vo);
				});
				result = finalResult.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(e -> e.getId() + ";" + e.getName()))),ArrayList::new));
				result = result.stream().sorted(Comparator.comparing(MaintainTemplateSceneTypeVO::getSortTime).reversed()).collect(Collectors.toList());
			}
			userSchedulingConfigVO.setFinishedConfig(result);
			userSchedulingConfigVO.setUnfinishedConfig(new ArrayList<>());
			userSchedulingConfigVO.setDisableConfig(new ArrayList<>());
			return userSchedulingConfigVO;
		}
		return userSchedulingConfigVO;
	}

		/**
		 * 查询当前用户配置信息
		 * @return 配置信息
		 */
		@Override
		public UserSchedulingConfigVO listConfig () {
			// 0. 数据准备,当前用户id
			Long currentUserId = AuthUtil.getUserId();
			// 1. 根据当前用户id，查询是否存在配置信息，存在则返回，不存在则返回空
			UserSchedulingConfig config = this.getOne(new LambdaQueryWrapper<UserSchedulingConfig>()
				.eq(UserSchedulingConfig::getUserId, currentUserId)
				.eq(UserSchedulingConfig::getIsDeleted, 0)
			);
			if (Func.isNull(config)) {
				return null;
			}
			String configJson = config.getConfig();
			// 2. 将Json格式转换成对象
			UserSchedulingConfigVO userSchedulingConfigVO = JSON.parseObject(configJson, UserSchedulingConfigVO.class);
			userSchedulingConfigVO.setUserId(currentUserId);
			if(Func.isNull(userSchedulingConfigVO.getDisableConfig())){
				userSchedulingConfigVO.setDisableConfig(new ArrayList<>());
			}
			if(Func.isNull(userSchedulingConfigVO.getFinishedConfig())){
				userSchedulingConfigVO.setFinishedConfig(new ArrayList<>());
			}
			if(Func.isNull(userSchedulingConfigVO.getUnfinishedConfig())) {
				userSchedulingConfigVO.setUnfinishedConfig(new ArrayList<>());
			}
			return userSchedulingConfigVO;
		}


	}
